package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.MemberCardRefund;
import com.finance.mapper.MemberCardRefundMapper;
import com.finance.service.MemberCardRefundService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C12
 * 会员卡退卡数据Service实现类
 */
@Slf4j
@Service
public class MemberCardRefundServiceImpl extends ServiceImpl<MemberCardRefundMapper, MemberCardRefund> implements MemberCardRefundService {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            log.warn("No records to process for C12 data");
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                .eq(MemberCardRefund::getSearchDate, searchDate)
                .eq(MemberCardRefund::getCinemaId, cinemaId)
                .count();
            if (count > 0) {
                log.info("C12数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                .eq(MemberCardRefund::getSearchDate, searchDate)
                .eq(MemberCardRefund::getCinemaId, cinemaId)
                .remove();
        }

        List<MemberCardRefund> refundList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                MemberCardRefund refund = new MemberCardRefund();
                refund.setCinemaId(cinemaId);
                //退卡影城名称,退卡影城编码,退卡日期,订单号,卡号,卡类型,卡类型编码,卡政策,卡政策编码
                if (StringUtils.hasText(record.get("退卡影城名称"))) {
                    refund.setRefundCinemaName(record.get("退卡影城名称"));
                }
                if (StringUtils.hasText(record.get("退卡影城编码"))) {
                    refund.setRefundCinemaCode(record.get("退卡影城编码"));
                }
                // 处理退卡日期
                String refundDateStr = record.get("退卡日期");
                if (StringUtils.hasText(refundDateStr)) {
                    try {
                        refund.setRefundDate(LocalDate.parse(refundDateStr, DATE_FORMATTER));
                    } catch (Exception e) {
                        log.warn("Invalid refund date format: {}", refundDateStr);
                    }
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    refund.setOrderNo(record.get("订单号"));
                }
                if (StringUtils.hasText(record.get("卡号"))) {
                    refund.setCardNo(record.get("卡号"));
                }
                if (StringUtils.hasText(record.get("卡类型"))) {
                    refund.setCardType(record.get("卡类型"));
                }
                if (StringUtils.hasText(record.get("卡类型编码"))) {
                    refund.setCardTypeCode(record.get("卡类型编码"));
                }
                if (StringUtils.hasText(record.get("卡政策"))) {
                    refund.setCardPolicy(record.get("卡政策"));
                }
                if (StringUtils.hasText(record.get("卡政策编码"))) {
                    refund.setCardPolicyCode(record.get("卡政策编码"));
                }
                // 退卡前余额,退卡退还工本费,退卡金额
                // 处理退卡前余额
                String balanceBeforeRefundStr = record.get("退卡前余额");
                if (StringUtils.hasText(balanceBeforeRefundStr)) {
                    try {
                        refund.setBalanceBeforeRefund(new BigDecimal(balanceBeforeRefundStr));
                    } catch (Exception e) {
                        log.warn("Invalid balance before refund format: {}", balanceBeforeRefundStr);
                    }
                }
                // 处理退卡退还工本费
                String refundCardFeeStr = record.get("退卡退还工本费");
                if (StringUtils.hasText(refundCardFeeStr)) {
                    try {
                        refund.setRefundCardFee(new BigDecimal(refundCardFeeStr));
                    } catch (Exception e) {
                        log.warn("Invalid refund card fee format: {}", refundCardFeeStr);
                    }
                }
                
                // 处理退卡金额
                String refundAmountStr = record.get("退卡金额");
                if (StringUtils.hasText(refundAmountStr)) {
                    try {
                        refund.setRefundAmount(new BigDecimal(refundAmountStr));
                    } catch (Exception e) {
                        log.warn("Invalid refund amount format: {}", refundAmountStr);
                    }
                }
                // 支付工具,支付工具编码,退卡手续费,退卡手续费支付工具,退卡手续费支付工具编码,操作员,操作员工号
                if (StringUtils.hasText(record.get("支付工具"))) {
                    refund.setPaymentTool(record.get("支付工具"));
                }
                if (StringUtils.hasText(record.get("支付工具编码"))) {
                    refund.setPaymentToolCode(record.get("支付工具编码"));
                }
                
                // 处理退卡手续费
                String refundFeeStr = record.get("退卡手续费");
                if (StringUtils.hasText(refundFeeStr)) {
                    try {
                        refund.setRefundFee(new BigDecimal(refundFeeStr));
                    } catch (Exception e) {
                        log.warn("Invalid refund fee format: {}", refundFeeStr);
                    }
                }
                
                if (StringUtils.hasText(record.get("退卡手续费支付工具"))) {
                    refund.setRefundFeePaymentTool(record.get("退卡手续费支付工具"));
                }
                if (StringUtils.hasText(record.get("退卡手续费支付工具编码"))) {
                    refund.setRefundFeePaymentToolCode(record.get("退卡手续费支付工具编码"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    refund.setOperator(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("操作员工号"))) {
                    refund.setOperatorEmployeeNo(record.get("操作员工号"));
                }
                // 发卡影院,发卡影城编码,会员ID
                if (StringUtils.hasText(record.get("发卡影院"))) {
                    refund.setIssueCinema(record.get("发卡影院"));
                }
                if (StringUtils.hasText(record.get("发卡影城编码"))) {
                    refund.setIssueCinemaCode(record.get("发卡影城编码"));
                }
                if (StringUtils.hasText(record.get("会员ID"))) {
                    refund.setMemberId(record.get("会员ID"));
                }
                refund.setSearchDate(searchDate);
                
                refundList.add(refund);
            } catch (Exception e) {
                log.error("Error processing C12 record: {}", record, e);
                throw new RuntimeException("Failed to process C12 record", e);
            }
        }

        try {
            saveBatch(refundList);
            return refundList.size();
        } catch (Exception e) {
            log.error("Error saving C12 data batch", e);
            throw new RuntimeException("Failed to save C12 data batch", e);
        }
    }
} 